using ActiveDs;
using System;
using System.Collections;
using System.Collections.Generic;

using System.DirectoryServices;

using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;

namespace zevenseas.Community.Web.UI.WebControls.WebParts
{
    /// <summary>
    ///     ChangePassword: TODO: 
    /// </summary>        
    public class ChangePassword : System.Web.UI.WebControls.WebParts.WebPart, IWebEditable
    {
        #region Private properties

        private TextBox oldpassword;
        private TextBox newpassword;
        private TextBox checknewpassword;
        private RegularExpressionValidator val;

        private LinkButton btn;
        private Label output;

        private string domain;

        #endregion Private properties

        [WebBrowsable(false), WebDisplayName("Domain")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("ChangePassword Settings")]
        [DefaultValue("")]
        public string Domain
        {
            get { return domain; }
            set
            {
                domain = value;
            }
        }

       
      

        #region Public properties
        
        #endregion Public properties

        #region Protected properties

        protected override void CreateChildControls()
        {
            //this.Title = "ChangePassword";

            this.oldpassword = new TextBox();
            this.oldpassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(oldpassword);

            this.newpassword = new TextBox();
            this.newpassword.ID = "newpassword";
            this.newpassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(newpassword);

            this.checknewpassword = new TextBox();
            this.checknewpassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(checknewpassword);
                       
            this.btn = new LinkButton();
            this.btn.Click += new EventHandler(btn_Click);
            this.btn.Text = "Change Password";
            this.Controls.Add(btn);

            this.output = new Label();
            this.Controls.Add(output);

            base.CreateChildControls();
        }

        protected string GetToolPaneLink()
        {
            bool hasRights = ((ISecurableObject)SPContext.Current.Web).DoesUserHavePermissions((SPBasePermissions)Microsoft.SharePoint.SPPermissionGroup.WebDesigner);

            if (!hasRights)
                return "Web Part has not been configured";

            string editLink = ToolPane.GetShowExtensibleToolPaneEvent(string.Format(@"'{0}'", this.UniqueID));
            editLink = string.Format(@"javascript:{0}", editLink.Replace(@"ExtensibleView", @"Edit"));
            return editLink;
        } 

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (string.IsNullOrEmpty(domain))
            {
                Literal configWebPart = new Literal();
                configWebPart.Text = "To configure this web part, <a href=" + GetToolPaneLink() +
                                     ">open the tool pane</a> and then configure the domain name";
                configWebPart.RenderControl(writer);
                return;
            }
            else
            {

                string strLoginName = string.Empty;

                try
                {
                    SPWeb webContext = SPControl.GetContextWeb(Context);
                    strLoginName = webContext.CurrentUser.LoginName;
                }
                catch (Exception)
                {
                    output.Text += "<BR> Please sign in first using the 'Sign In' button above";
                }

                //I know, i know.. i need to do this properly ;)
                if (strLoginName != string.Empty)
                {
                    writer.Write("<table border=0>");
                    writer.Write("<tr>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("Current password:");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    oldpassword.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("</tr>");
                    writer.Write("<tr valign='top'>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("New password:");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    newpassword.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("</tr>");
                    writer.Write("<tr valign='top'>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("Confirm new password:");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    checknewpassword.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</tr>");
                    writer.Write("<tr valign='top'>");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    btn.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("</tr>");
                    writer.Write("</table>");
                    output.RenderControl(writer);
                }
                else { output.RenderControl(writer); }
            }

        }

        #endregion Protected properties

        #region  Public methods

        #endregion Public methods

        #region Protected methods

        #endregion Protected methods

        #region Private methods

        #endregion Private methods

        #region Events

        void btn_Click(object sender, EventArgs e)
        {
            output.Text = string.Empty;

            if (newpassword.Text.Length >= 7)
            {
                if (newpassword.Text.ToString() == checknewpassword.Text.ToString())
                {
                    SPWeb webContext = SPControl.GetContextWeb(Context);
                    string strLoginName = webContext.CurrentUser.LoginName;
                    int iPosition = strLoginName.IndexOf("\\") + 1;
                    strLoginName = strLoginName.Substring(iPosition);

                    DirectoryEntry entry = new DirectoryEntry();
                    SearchResultCollection results = null;
                    try
                    {
                        entry = new DirectoryEntry("LDAP://"+ domain, strLoginName, oldpassword.Text.ToString(), AuthenticationTypes.Secure);
                        DirectorySearcher search = new DirectorySearcher(entry);
                        search.Filter = "(SAMAccountName=" + strLoginName + ")";
                        search.SearchScope = SearchScope.Subtree;
                        search.CacheResults = false;

                        results = search.FindAll();
                    }

                    catch (Exception error)
                    {
                        output.Text += "<BR><B>" + error.InnerException.Message.ToString() + "</B>";
                       
                    }

                    if (results.Count > 0)
                    {
                        foreach (SearchResult result in results)
                        {
                            try
                            {
                                entry = result.GetDirectoryEntry();
                            }
                            catch (Exception error)
                            {
                                output.Text += "<BR><B>" + error.Message.ToString() + "</B>";
                                
                            }

                        }

                        try
                        {

                            //PublishInList(oldpasswordHash, newpasswordHash);

                            entry.Invoke("ChangePassword", new object[] { oldpassword.Text.ToString(), newpassword.Text.ToString() });
                            entry.CommitChanges();

                            output.Text += "<BR><B> Password is changed </B>";
                        }
                        catch (Exception error)
                        {

                            //output.Text += "<b> Password couldn't be changed due to restrictions<b>";
                            output.Text += "<BR><B>Password couldn't be changed due to the following error : <BR>" + error.InnerException.Message.ToString() + "</B><BR><BR>";
                            
                        }
                    }
                    else
                    {

                        output.Text += "<BR><B> User not found or bad password</B>";
                        
                    }
                }

                else
                {
                    output.Text += "<BR><B>Passwords don't match</B>";
                    

                }
            }
            else
            {
                output.Text += "<BR><B>Your password must be a minimum of 8 characters.</B>";
                
            }

        }

        #endregion Events

        #region IWebEditable Members

        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();

            EditorPart changePasswordEditor = new ChangePasswordEditor();
            changePasswordEditor.ID = "changePasswordEditor" + this.ID;

            editors.Add(changePasswordEditor);
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }

        #endregion

    }
}
